<template>
  <div class="content">
    <p @click="wxPay">立即领取</p>
    <p @click="jumpPage">跳到成功页面</p>
  </div>
</template>
<script>
import {
  getUserInfoByCode,
  getBidType,
  enter_loadH5,
  wxJsPay,
  getJsTicket,
  getCodeLock,
} from "@/assets/mp";
import { getSign, getQuery,getHeadersParams } from "@/assets/utils";
import { mpList } from "@/assets/mp-list";
import { mapState } from "vuex";
// import wx from 'wx';
export default {
  data() {
    return {
      qrCodeUrl:''
    };
  },
  computed: {
    ...mapState(["pageInfo", "userInfo"]),
    //   获取公众号信息
    mpInfo() {
      const mpIdx = Number.parseInt(getQuery(this, "mpIdx"));
      const info = mpList.find((item) => item.id === mpIdx);
      return info;
    },
    // 微信登录授权链接
    authorizeUrl() {
      const { appId } = this.mpInfo;
      const href = encodeURIComponent(window.location.href);
      return `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${href}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect`;
    },
  },
  methods: {
    async wxPay() {
      const params = {
        merchantCode: 1001,
        // serverId: this.mpInfo.serverId,
        serverId: 10091001,
        platformNo: "wechat",
        productNo: "008",
        productTitle: "VIP投资大礼包",
        amount: 1,
        bid: this.pageInfo.bid,
        sid: this.pageInfo.sid,
        refferId: this.pageInfo.reffer,
        channel: this.pageInfo.channel,
        openid: this.userInfo.openId,
        bizType: this.pageInfo.bizType,
        appId: this.pageInfo.appId,
      };
      const res = await wxJsPay(params);
      console.log(res);
    },

    //获取页面基本信息并存储到vuex
    getPageInfo() {
      const code = getQuery(this, "code");
      const bid = getQuery(this, "bid");
      this.$store.commit("getPageInfo", {
        code,
        bid,
        appId: this.mpInfo.appId,
        reffer: this.mpInfo.reffer,
        sid: this.mpInfo.sid,
        channel: "mp",
        mpName: this.mpInfo.mpName,
      });
    },
    //链接中没有拼接code参数则进行授权操作
    authorize() {
      return new Promise((resolve) => {
        if (!this.pageInfo.code) {
          window.location.href = this.authorizeUrl;
          resolve();
        } else {
          resolve();
        }
      });
    },
    // 获取用户的信息
    async getUserInfo() {
      const params = {
        channelId: this.mpInfo.channelId,
        serverId: "116",
        activityId: this.pageInfo.sid,
        reffer: this.pageInfo.reffer,
      };
      let { openId, unionid, nickname, headImage } = await getUserInfoByCode(
        params,
        this.pageInfo.code
      );
      this.$store.commit("getUserInfo", {
        openId,
        unionid,
        nickname,
        headImage,
      });
    },
    //通过bid获取业务类型，保存到pageInfo中
    async getBizType() {
      const { data } = await getBidType(this.pageInfo.bid);
      this.$store.commit("getPageInfo", {
        bizType: data.bizType,
      });
    },

    // 进入落地页收集信息
    async enterLandingPage() {
      const params = {
        channel: "mp",
        reffer: this.pageInfo.reffer,
        sid: this.pageInfo.sid,
        bid: this.pageInfo.bid,
        mtraceId: "",
        appId: this.pageInfo.appId,
        openId: this.userInfo.openId,
        unionId: this.userInfo.unionid,
        pageUrl: window.location.href,
      };
      console.log(params);
      console.log(getSign(params, this));
      console.log(getHeadersParams(this.pageInfo.bizType).serverId);
      console.log('==========================================');
      let headers = {
        "Content-Type": "application/json",
        serverId: getHeadersParams(this.pageInfo.bizType).serverId,
        sign: getSign(params, this),
      };
      const res = await enter_loadH5(params, headers);
      console.log(res);
    },

    //一客一码锁定
    async codeLock(){
            let params = {
        channel: 'mp',
        openId: this.userInfo.openId
      };
      const  headers={
            serverId: getHeadersParams(this.pageInfo.bizType).serverId,
            sign: getSign(params,this)
          }
      const res = await getCodeLock(params,this.pageInfo.bizType,headers)
      this.qrCodeUrl = res.data == null ? '' : res.data;
    } ,

    // jsTicket权限验证
    async wxConfig() {
      // 获取jsTicket
      const href = window.location.href;
      const params = {
        channelId: this.mpInfo.channelId,
        url: href.substring(0, href.indexOf("#")),
      };
      const jsTicket = await getJsTicket(params);
      wx.config({
        debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
        appId: jsTicket.appId, // 必填，公众号的唯一标识
        timestamp: jsTicket.timestamp, // 必填，生成签名的时间戳
        nonceStr: jsTicket.nonceStr, // 必填，生成签名的随机串
        signature: jsTicket.signature, // 必填，签名
        jsApiList: ["hideOptionMenu", "chooseWXPay"], // 必填，需要使用的JS接口列表
      });
      wx.ready(function () {
        wx.checkJsApi({
          jsApiList: ["hideOptionMenu", "chooseWXPay"],
          success(res) {
            console.log(res);
          },
        });
        // 禁用菜单栏功能
        wx.hideOptionMenu();
      });
      wx.error(function (err) {
        console.warn(err);
      });
    },

    // 跳到支付成功页面
    jumpPage() {
      this.$router.push({
        name: "220402success",
        params: {
          ...this.pageInfo,
          ...this.userInfo,
          id: 1,
          qrCodeUrl: this.qrCodeUrl
        },
      });
    },
  },

  async created() {
    wx.hideOptionMenu();
    //  存储页面信息
    this.getPageInfo();
    // 授权获取code
    await this.authorize();
    // 获取用户的信息
    await this.getUserInfo();
    // 获取业务类型
    await this.getBizType();
    // 进入落地页收集信息
    await this.enterLandingPage();
    // 一客一码锁定
    await this.codeLock()
    // jsTicket权限验证
    this.wxConfig();
  },
  mounted() {
    console.log(this.$store);
  },
};
</script>
<style lang="less" scoped>
p {
  text-align: center;
  font-size: 50px;
  color: blue;
  margin-top: 30px;
}
</style>
